package com.example.jacky.android_easeui.netapi.retrofit;


import android.os.SystemClock;
import android.text.TextUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ljr on 2016/3/24.
 * 调用网络接口
 */
public class ServiceFactory {
    public static final String mBaseUrl = "http://192.168.2.203:8081/api/v1/";
    //    public static final String mBaseUrl = Key.URL_REQUEST_NET;
    protected static final Object monitor = new Object();

    /*    //缓存容量
      static long SIZE_OF_CACHE = 10 * 1024 * 1024; // 10 MiB
      //缓存路径
      static Cache cache = new Cache(FileUtils.getCacheDir(), SIZE_OF_CACHE);*/
    private static RetrofitService sRetrofitService;

    private static HttpLoggingInterceptor httpLoggingInterceptor =
            new HttpLoggingInterceptor()
                    .setLevel(HttpLoggingInterceptor.Level.BODY
                    );

    private static Interceptor headerInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            SystemClock.sleep(500);

            if (TextUtils.isEmpty(chain.request().header("Authorization"))) {
                builder.addHeader("Authorization","eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdHRyaWJ1dGVzIjp7ImVtYWlscyI6W10sImdlbmRlciI6Im51bGwiLCJ1c2VySWQiOiI1ODE5NGRmMjE2Yzg3ZGE0NzRmMmUxNTMiLCJtb2JpbGVzIjpbXSwidXNlcm5hbWUiOiIxMDAwMDAwMDEwNCIsImxvZ2luVHlwZSI6IndlY2hhdCIsImV4dFBhcmFtcyI6e319LCJleHAiOjE0NzkxMzM4NjUsInVzZXJfbmFtZSI6IjU4MTk0ZGYyMTZjODdkYTQ3NGYyZTE1MyIsImp0aSI6IjZjYmZjNDQzLTBiZGUtNDhjMS1iOTliLTI4NjI0YTczODRiZCIsImNsaWVudF9pZCI6InVwbHVzZ28iLCJzY29wZSI6WyJvcGVuaWQiLCJ3cml0ZSIsInJlYWQiLCJzb3BfYmFzZSIsInNvcF91c2hvcCIsInNvcF9zdW5iYXIiLCJzb3BfdWFjIiwic29wX21lcmNoYW50Iiwic29wX3B1c2giLCJzb3BfYWNjb3VudCJdfQ.FaFn7otkkglxzOLgEgPPDfe0nIzZQCgQKldKgYZG4eHxKQ5H13yC30VGP_ONYPQwWOoFSeeBGQmPRyXD1bI2smywqaQk1wj5obN_uE7LcuVGu7e40Nr52Arm4Am3xE886BiayTWm1Acm8tQozbHU8d9JAbWgDMXWnC1mk0TVf5RKHBc7uWVlpS6Om0sBP8HJll_0ex7j__sJMEhO6lO8hiaSpNtEH8QswGh2PfAgL2INsHHce5z517nDbfvvF_js6RypHT6IxIof4iAuFBoCwORZgLGbWQZnkWANlMpwxEo-j-tNdXi3ivca6Y5IIK6eN5i60ernwCQZvjQQ1A6rrg");
            }

            Response response = chain.proceed(builder.build());
            return response;
        }
    };

    private static OkHttpClient shttpClient =
            new OkHttpClient()
                    .newBuilder()
//                    //有网络时的拦截器
//                    .addNetworkInterceptor(ServiceFactory.REWRITE_RESPONSE_INTERCEPTOR)
//                    //没网络时的拦截器
//                    .addInterceptor(ServiceFactory.REWRITE_RESPONSE_INTERCEPTOR_OFFLINE)
                    .addInterceptor(httpLoggingInterceptor)
                    .addInterceptor(headerInterceptor)
//                    .cache(cache)
                    .build();

    private static Retrofit retrofit = new Retrofit
            .Builder()
            .client(shttpClient)
            .baseUrl(mBaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

    private static Retrofit retrofitOthers = null;

    public static <T> T createService(Class<T> serviceClass, String url) {
        retrofitOthers = new Retrofit
                .Builder()
                .client(shttpClient)
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofitOthers.create(serviceClass);
    }

    public static RetrofitService getRetrofitService() {
        if (sRetrofitService == null) {
            synchronized (monitor) {
                if (sRetrofitService == null) {
                    sRetrofitService = retrofit.create(RetrofitService.class);
                }
            }
        }
        return sRetrofitService;
    }


    private static final int TIMEOUT_CONNECT = 5; //5秒
    private static final int TIMEOUT_DISCONNECT = 60 * 60 * 24 * 7; //7天

    public static final Interceptor REWRITE_RESPONSE_INTERCEPTOR = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            //获取retrofit @headers里面的参数，参数可以自己定义，在本例我自己定义的是cache，跟@headers里面对应就可以了
            String cache = chain.request().header("cache");
            okhttp3.Response originalResponse = chain.proceed(chain.request());
            String cacheControl = originalResponse.header("Cache-Control");
            //如果cacheControl为空，就让他TIMEOUT_CONNECT秒的缓存，本例是5秒，方便观察。注意这里的cacheControl是服务器返回的
            if (cacheControl == null) {
                //如果cache没值，缓存时间为TIMEOUT_CONNECT，有的话就为cache的值
                if (cache == null || "".equals(cache)) {
                    cache = TIMEOUT_CONNECT + "";
                }
                originalResponse = originalResponse.newBuilder()
                        .header("Cache-Control", "public, max-age=" + cache)
                        .build();
                return originalResponse;
            } else {
                return originalResponse;
            }
        }
    };

    public static final Interceptor REWRITE_RESPONSE_INTERCEPTOR_OFFLINE = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            //离线的时候为7天的缓存。
     /*       if (!CommonUPlusgoUtils.isNetWorkConnected()) {
                request = request.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + TIMEOUT_DISCONNECT)
                        .build();
            }*/
            return chain.proceed(request);
        }
    };

}
